<template>
    <div>
        <el-card class="box-card">
            <!-- 头部(输入框,查询,清空) -->
            <div class="top">
                <el-input 
                    v-model="input" 
                    class="input" 
                    placeholder="用户名" 
                    clearable size="small"
                ></el-input>

                <el-button 
                    @click="getById"
                    class="btn_query" 
                    size="small" 
                    type="primary" 
                    icon="el-icon-search"
                >查询</el-button>

                <el-button 
                    size="small"
                    @click="clear"
                >清空</el-button>
            </div>


            <!-- middle: 中间的(添加,批量删除) -->
            <div class="middle">
                <el-button 
                    class="btn_add" 
                    type="primary" 
                    size="small"
                    @click="add"
                >添加</el-button>

                <el-button 
                    type="danger" 
                    size="small" 
                    disabled
                >批量删除</el-button>
            </div>


            <!-- 表格 和 操作功能 -->
            <div class="bottom">
                <el-table 
                    ref="multipleTable" 
                    :data="tableData.items"
                    tooltip-effect="dark" 
                    style="width: 100%;" 
                    border
                >
                    <el-table-column type="selection" width="60px"></el-table-column>
                    <el-table-column label="序号" type="index" width="80px">
                    </el-table-column>
                    <el-table-column prop="username" label="用户名"></el-table-column>
                    <el-table-column prop="nickName" label="用户昵称"></el-table-column>
                    <el-table-column prop="roleName" label="角色列表"></el-table-column>
                    <el-table-column prop="gmtCreate" label="创建时间"></el-table-column>
                    <el-table-column prop="gmtModified" label="更新时间">
                    </el-table-column>

                    <el-table-column label="操作" width="200px">
                        <template v-slot="{ row, $index }">

                        <!-- 设置角色 -->
                        <el-button
                            type="info"
                            icon="el-icon-user-solid"
                            size="mini"
                            @click="addRoleMethod(row.id)"
                        ></el-button>
                        <!-- 修改用户 -->
                        <el-button
                            @click="updateUser(row)"
                            type="primary"
                            icon="el-icon-edit-outline"
                            size="mini"
                        ></el-button>
                        <!-- 删除用户 -->
                        <el-button
                            @click="open(row)"
                            type="danger"
                            icon="el-icon-delete"
                            size="mini"
                        ></el-button>
                        </template>
                    </el-table-column>
                    
                </el-table>
            </div>


            <!-- 分页组件 -->
            <div class="block">
                <el-pagination 
                    @size-change="handleSizeChange" 
                    @current-change="handleCurrentChange"
                    :current-page="currentPage" 
                    :page-sizes = '[5,10,15,20]'
                    :page-size="100" 
                    layout=" prev, pager, next, jumper,->, sizes,total"
                    :total="tableData.total"
                >
                </el-pagination>
            </div>


            <!-- 抽屉组件 -->
            <el-drawer
                title="添加用户"
                :visible.sync="drawer"
                direction="ttb"
                :with-header="true"
                size="150"
                :before-close="handleClose"
            >
                <el-form 
                    :model="addUser" 
                    status-icon 
                    :rules="rules" 
                    ref="ruleForm" 
                    label-width="100px" 
                >
            <!-- 抽屉-用户名 -->
            <el-form-item 
                label="用户名" 
                prop="username"
            >
                <el-input 
                    v-model="addUser.username" 
                    placeholder="请输入用户名"
                ></el-input>
            </el-form-item>

            <!-- 抽屉-用户昵称 -->
            <el-form-item 
                    label="用户昵称" 
                    prop="nameNick"
            >
                <el-input 
                    v-model="addUser.nickName"
                    placeholder="请输入用户昵称"
            ></el-input>
            </el-form-item>

            <!-- 抽屉-用户密码 -->
            <el-form-item 
                    label="用户密码" 
                    prop="password"
            >
                <el-input 
                    v-model="addUser.password"
                    placeholder="请输入用户密码"
            ></el-input>
            </el-form-item>
            
            <el-form-item>
                <el-button type="primary" @click="confirmAdd">提交</el-button>
                <el-button @click="cancleAdd">取消</el-button>
            </el-form-item>
            </el-form>

            </el-drawer>


            <!-- 点击设置角色的对话框 -->
            <el-dialog 
                title="设置角色" 
                :visible.sync="dialogFormVisible"
            >

                <el-form :model="addRole">

                <el-form-item label="用户名">
                    <el-input 
                        v-model="addRole.name"
                    ></el-input>
                </el-form-item>

                <el-form-item label="角色列表">
                    <el-checkbox
                        :indeterminate="isIndeterminate"
                        v-model="checkAll"
                        @change="handleCheckAllChange"
                    >全选</el-checkbox>

                    <div style="margin: 15px 0"></div>

                    <el-checkbox-group
                        v-model="roles.assignRoles"
                        @change="handleCheckedCitiesChange"
                    >

                    <el-checkbox
                        v-for="role in roles.allRolesList"
                        :label="role.roleName"
                        :key="role.id"
                        >{{ role.roleName }}
                    </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="uploadRoles">确 定</el-button>
                </div>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
import userApi from "@/api/acl/user";

export default {
    name: "UsersControl",

    // 数据
    data() {
        return {
            input: '',
            // 用户数据
            tableData: {},
            // 目前第几页
            currentPage: 1,
            // 每页有几条数据
            pageSize: 5,
            // 抽屉
            drawer: false,
            addUser: {
                username: '',
                nickName: '',
                password: '',
            },
            rules: {
                username: [
                    //required: 必须的      message: 报文                 trigger:  焦点 
                    { required: true,       message: '请输入用户名',      trigger: 'blur' },
                    {
                        min: 6,
                        max: 20,
                        message: '用户名长度在 6 到 20 个字符',
                        trigger: blur
                    }

                ],
                password: [
                    { required: true,        message: '请输入密码',        trigger: 'blur' },
                    {
                        min: 5,
                        max: 15,
                        message: '密码长度在 5 到 15 个字符',
                        trigger: blur
                    }
                ]
                
            },
            // 对话框体可见 - 默认为不可见
            dialogFormVisible: false,
            addRole: {},
            checkAll: false,
            isIndeterminate: true,
            roles: {},
            checkedRoles: "",
            echoUser: [],
            isUpdate: false,
            multipleSelection: [],
        }
    },


    // 方法
    methods: {
        // 批量删除弹出确认框
        deleteManyUsersOpen() {
        this.$confirm("此操作将永久删除这些, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
            .then(() => {
            this.deleteManyUsers();
            this.$message({
                type: "success",
                message: "删除成功!",
            });
            })
            .catch(() => {
            this.$message({
                type: "info",
                message: "已取消删除",
            });
            });
        },

        // 点击批量删除按钮
        async deleteManyUsers() {
        try {
            await userApi.removeUsers(this.multipleSelection);
            this.$message({
            message: "删除成功",
            type: "success",
            });
        } catch (error) {
            console.log(456);
            this.$message.error("删除失败");
        }
        },

        // 点击多选框后收集到被点击的那一项
        handleSelectionChange(val) {
        this.multipleSelection = val;
        },


        // 点击删除弹窗
        open(row) {
            // 双重效验: 第一重
            this.$confirm("此操作将永久删除该用户,是否继续?,提示", {
                confirmButtonText:"确定",
                cancelButtonText: "取消"
            })
            .then(() => {
                // 删除用户的回调
                this.deleteUser(row.id);
                // 用于删除获取用户里的数据回调
                this.getUsers();
                // 删除成功和删除失败的提示
                this.$message({
                    type:"success ",
                    message: "删除成功"
                });
            })
            .catch(() => {
                // 未执行删除用户回调
                this.$message({
                    type: "text",
                    message: "删除失败"
                })
            })
        },


        // 删除用户的回调
        async deleteUser(id) {
            await userApi.removeById(id);
        },


        // 修改用户的回调
        updateUser(row) {
            this.drawer = true;
            this.addUser = row;
            this.isUpdate = true;
        },


        // 分配角色对话框点击确定按钮
        async uploadRoles(userId, roleId) {
            await userApi.assignRoles(userId, roleId)
            dialogFormVisible = false
        },


        // 修改用户的确定按钮
        async confirmUpdateUser() {
        try {
            await userApi.update(this.addUser);
            this.drawer = false;
            this.$message({
            message: "修改成功",
            type: "success",
            });
            this.addUser = {
            username: "",
            nickName: "",
            password: "",
            };
        } catch (error) {
            this.$message.error("修改失败");
        }
        },


        //  点击切换每页条数
            handleSizeChange(val) {
            this.pageSize = val;
            this.getUsers();
          },


        // 跳转到第几页
          handleCurrentChange(val) {
            this.currentPage = val
            this.getUsers();
          },


        //   获取用户
        async getUsers() {
            const result = await userApi.getPageList(
                this.currentPage,
                this.pageSize,
                this.input
            )
            this.tableData = result.data
        },


        // 搜索回调
        getById() {
            this.getUsers();
        },


        // 清空input回调
        clear() {
            this.input = '',
            this.getUsers();
        },


        // 点击触发抽屉的回调
        add() {
            this.drawer = true
        },


        // 抽屉的提交按钮
        confirmAdd() {

        },


        // 抽屉的取消按钮
        cancleAdd() {
            this.drawer = false
            this.getUsers()
        },


        // 抽屉点击遮罩层外关闭的回调
        handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
        },


        // 添加角色按钮
        addRoleMethod(id) {
            this.allRoles(id)
            this.dialogFormVisible = true
        },


        // 点击全选
        handleCheckAllChange() {

        },


        // 点击单选
        handleCheckedCitiesChange(value) {
            let checkedCount = value.length;
            this.checkAll = checkedCount === this.assignRoles.length;
            this.isIndeterminate =
                checkedCount > 0 && checkedCount < this.cities.length;
            this.checkedRoles.join(role.id);
        },



        // 获取全部角色  (抽屉里)
        async allRoles(id) {
            let result = await userApi.getRoles(id);
            this.roles = result.data;
        },


    },


        mounted() {
        this.getUsers();
      },

}
</script>

<style lang="scss" scoped>
.top {
    .input {
        width: 200px;
        margin-right: 50px;
    }

    .btn_query {
        margin-right: 5px;
    }
}

.middle {
    margin-top: 30px;

    .btn_add {
        margin-right: 10px;
    }
}

.bottom {
    margin-top: 30px;
}
</style>